// internal/infrastructure/logger/logger.go
package logger

import (
	"log"
	"os"
	"path/filepath"
	"sync"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var (
	logger *zap.Logger
	once   sync.Once
)

// Init 初始化日志
func Init() {
	once.Do(func() {
		// 创建日志目录
		logDir := "./logs"
		os.MkdirAll(logDir, 0755)

		logFile := filepath.Join(logDir, "app.log")
		file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			log.Printf("Failed to open log file, using stdout only: %v", err)
			file = os.Stdout
		}

		// 创建多写入器（文件+控制台）
		multiWriter := zapcore.NewMultiWriteSyncer(
			zapcore.AddSync(os.Stdout),
			zapcore.AddSync(file),
		)

		encoderConfig := zap.NewProductionEncoderConfig()
		encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder

		core := zapcore.NewCore(
			zapcore.NewJSONEncoder(encoderConfig),
			multiWriter,
			zapcore.DebugLevel,
		)

		logger = zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))
	})
}

// Get 获取logger实例
func Get() *zap.Logger {
	return logger
}

// Info 记录info级别日志
func Info(msg string, fields ...zap.Field) {
	if logger != nil {
		logger.Info(msg, fields...)
	} else {
		log.Println("[INFO]", msg)
	}
}

// Error 记录error级别日志
func Error(msg string, fields ...zap.Field) {
	if logger != nil {
		logger.Error(msg, fields...)
	} else {
		log.Println("[ERROR]", msg)
	}
}

// Debug 记录debug级别日志
func Debug(msg string, fields ...zap.Field) {
	if logger != nil {
		logger.Debug(msg, fields...)
	} else {
		log.Println("[DEBUG]", msg)
	}
}
